<template>
  <div class="merchant-dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-s-home"></i>
        商家管理首页
      </h2>
      <p class="page-description">查看您的商家信息和用户数量统计</p>

      <!-- 生成聚合码按钮 -->
      <div class="header-actions">
        <el-button
          type="primary"
          icon="el-icon-qrcode"
          @click="generateAggregationCode"
          :loading="qrCodeLoading"
          class="qr-code-btn"
        >
          生成聚合码
        </el-button>
      </div>
    </div>

    <!-- 用户数量统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <!-- 当前锁定用户数量 -->
        <el-col :span="8">
          <el-card class="stats-card">
            <div class="card-content">
              <div class="card-icon">
                <i class="el-icon-user-solid"></i>
              </div>
              <div class="card-info">
                <div class="card-title">当前锁定用户</div>
                <div class="card-value">{{ userCountData.lockNum || 0 }}</div>
                <div class="card-unit">人</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 用户数量上限 -->
        <el-col :span="8">
          <el-card class="stats-card">
            <div class="card-content">
              <div class="card-icon limit-icon">
                <i class="el-icon-s-data"></i>
              </div>
              <div class="card-info">
                <div class="card-title">用户数量上限</div>
                <div class="card-value">{{ userCountData.lockNumLimit || 0 }}</div>
                <div class="card-unit">人</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 使用率 -->
        <el-col :span="8">
          <el-card class="stats-card">
            <div class="card-content">
              <div class="card-icon usage-icon">
                <i class="el-icon-time"></i>
              </div>
              <div class="card-info">
                <div class="card-title">使用率</div>
                <div class="card-value">{{ usageRate }}%</div>
                <div class="progress-container">
                  <el-progress
                    :percentage="usageRate"
                    :color="getUsageColor(usageRate)"
                    :show-text="false"
                    :stroke-width="8"
                  ></el-progress>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详细信息区域 -->
    <div class="info-section">
      <el-row :gutter="20">
        <!-- 商家基本信息 -->
        <el-col :span="12">
          <el-card class="info-card">
            <div slot="header" class="card-header">
              <span><i class="el-icon-user"></i> 商家基本信息</span>
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-refresh"
                @click="loadMerchantInfo"
                :loading="loading"
              >
                刷新数据
              </el-button>
            </div>

            <div class="info-content">
              <div class="info-item">
                <label>商家名称：</label>
                <span class="info-value">{{ merchantInfo.name || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>联系电话：</label>
                <span class="info-value">{{ merchantInfo.phone || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>邮箱地址：</label>
                <span class="info-value">{{ merchantInfo.email || '未设置' }}</span>
              </div>
              <div class="info-item">
                <label>商家编号：</label>
                <span class="info-value">{{ merchantInfo.salesmanNo || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>所属区域：</label>
                <span class="info-value">{{ merchantInfo.regionId || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>创建时间：</label>
                <span class="info-value">{{ merchantInfo.createTime || '未知' }}</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 银行卡信息 -->
        <el-col :span="12">
          <el-card class="info-card">
            <div slot="header" class="card-header">
              <span><i class="el-icon-credit-card"></i> 银行卡信息</span>
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-refresh"
                @click="loadBankCardInfo"
                :loading="loading"
              >
                刷新数据
              </el-button>
            </div>

            <div class="info-content" v-if="bankCardInfo">
              <div class="info-item">
                <label>银行名称：</label>
                <span class="info-value">{{ bankCardInfo.bankName || '未设置' }}</span>
              </div>
              <div class="info-item">
                <label>持卡人姓名：</label>
                <span class="info-value">{{ bankCardInfo.cardHolder || '未设置' }}</span>
              </div>
              <div class="info-item">
                <label>银行卡号：</label>
                <span class="info-value">
                  <span v-if="showFullCardNumber">{{ bankCardInfo.cardNumber }}</span>
                  <span v-else>{{ maskCardNumber(bankCardInfo.cardNumber) }}</span>
                  <el-button
                    type="text"
                    size="mini"
                    @click="toggleCardNumber"
                    class="toggle-btn"
                  >
                    {{ showFullCardNumber ? '隐藏' : '显示' }}
                  </el-button>
                </span>
              </div>
              <div class="info-item">
                <label>卡类型：</label>
                <span class="info-value">{{ bankCardInfo.cardType || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>开户行：</label>
                <span class="info-value">{{ bankCardInfo.bankBranch || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>更新时间：</label>
                <span class="info-value">{{ bankCardInfo.updateTime || '未知' }}</span>
              </div>
            </div>
            <div v-else class="no-data">
              <i class="el-icon-credit-card"></i>
              <p>暂无银行卡信息</p>
              <el-button type="primary" size="small" @click="goToBankCard">添加银行卡</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 使用率趋势图 -->
    <div class="chart-section">
      <el-card>
        <div slot="header" class="card-header">
          <span><i class="el-icon-pie-chart"></i> 使用率趋势</span>
        </div>
        <div class="chart-container">
          <div class="chart-content">
            <div class="donut-chart">
              <div class="chart-center">
                <div class="percentage">{{ usageRate }}%</div>
                <div class="label">使用率</div>
              </div>
            </div>
            <div class="chart-legend">
              <div class="legend-item">
                <div class="legend-color used"></div>
                <span>已使用: {{ userCountData.lockNum || 0 }} 人</span>
              </div>
              <div class="legend-item">
                <div class="legend-color remaining"></div>
                <span>剩余: {{ remainingCapacity }} 人</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 聚合码展示对话框 -->
    <el-dialog
      title="商家聚合码"
      :visible.sync="qrCodeDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      custom-class="qr-code-dialog"
    >
      <div class="qr-code-content">
        <div class="qr-code-info">
          <h3>{{ merchantInfo.name || '商家' }} 聚合码</h3>
          <p class="qr-code-desc">
            扫描此二维码可进行以下操作：<br>
            • 未下载app的用户可下载app<br>
            • 已下载app的用户可查看商品和结账<br>
            • 支持分页浏览商品（每页10条）
          </p>
        </div>

        <div class="qr-code-display" v-if="qrCodeUrl">
          <div class="qr-code-container">
            <img :src="qrCodeUrl" alt="聚合码" class="qr-code-image">
          </div>
          <div class="qr-code-actions">
            <el-button
              type="primary"
              icon="el-icon-download"
              @click="downloadQrCode"
            >
              下载二维码
            </el-button>
            <el-button
              type="success"
              icon="el-icon-refresh"
              @click="regenerateQrCode"
              :loading="qrCodeLoading"
            >
              重新生成
            </el-button>
          </div>
        </div>

        <div v-else class="qr-code-loading">
          <i class="el-icon-loading"></i>
          <p>正在生成聚合码...</p>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="qrCodeDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserInfo, getBankCardDetail, generateQrCode } from '@/api/aggregation'

export default {
  name: 'MerchantDashboard',
  data() {
    return {
      loading: false,
      userCountData: {
        lockNum: 0,
        lockNumLimit: 0,
        name: '',
        phone: ''
      },
      merchantInfo: {},
      bankCardInfo: null,
      showFullCardNumber: false,
      qrCodeDialogVisible: false,
      qrCodeLoading: false,
      qrCodeUrl: '',
      merchantId: null
    }
  },
  computed: {
    // 计算剩余容量
    remainingCapacity() {
      return (this.userCountData.lockNumLimit || 0) - (this.userCountData.lockNum || 0)
    },

    // 计算使用率
    usageRate() {
      const lockNum = this.userCountData.lockNum || 0
      const lockNumLimit = this.userCountData.lockNumLimit || 0
      if (lockNumLimit === 0) return 0
      return Math.round((lockNum / lockNumLimit) * 100)
    }
  },
  mounted() {
    this.loadAllData()
  },
  methods: {
    // 加载所有数据
    async loadAllData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadUserCountData(),
          this.loadMerchantInfo(),
          this.loadBankCardInfo()
        ])
      } catch (error) {
        Logger.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请重试')
      } finally {
        this.loading = false
      }
    },

    // 加载用户数量数据
    async loadUserCountData() {
      try {
        const response = await getUserInfo()
        if (response.code === 0 && response.data) {
          this.userCountData = {
            lockNum: response.data.lockNum || 0,
            lockNumLimit: response.data.lockNumLimit || 0,
            name: response.data.name || '',
            phone: response.data.phone || ''
          }
        }
      } catch (error) {
        Logger.error('加载用户数量数据失败:', error)
      }
    },

    // 加载商家信息
    async loadMerchantInfo() {
      try {
        const response = await getUserInfo()
        if (response.code === 0 && response.data) {
          this.merchantInfo = response.data
          // 设置商家ID用于生成聚合码
          this.merchantId = response.data.id || this.$store.state.user.id
          Logger.log('商家ID已设置:', this.merchantId)
        }
      } catch (error) {
        Logger.error('加载商家信息失败:', error)
      }
    },

    // 加载银行卡信息
    async loadBankCardInfo() {
      try {
        const response = await getBankCardDetail()
        if (response.code === 0 && response.data) {
          this.bankCardInfo = {
            ...response.data,
            cardHolder: response.data.name,
            cardNumber: response.data.cardNo
          }
        } else {
          this.bankCardInfo = null
        }
      } catch (error) {
        Logger.error('加载银行卡信息失败:', error)
        this.bankCardInfo = null
      }
    },

    // 切换银行卡号显示
    toggleCardNumber() {
      this.showFullCardNumber = !this.showFullCardNumber
    },

    // 遮罩银行卡号
    maskCardNumber(cardNumber) {
      if (!cardNumber) return '未设置'
      if (cardNumber.length <= 8) return cardNumber
      return cardNumber.substring(0, 4) + '****' + cardNumber.substring(cardNumber.length - 4)
    },

    // 获取使用率颜色
    getUsageColor(percentage) {
      if (percentage >= 90) return '#f56c6c'
      if (percentage >= 70) return '#e6a23c'
      if (percentage >= 50) return '#409eff'
      return '#67c23a'
    },

    // 跳转到银行卡管理
    goToBankCard() {
      this.$router.push('/merchant/bank-card')
    },

    // 生成聚合码
    async generateAggregationCode() {
      try {
        // 获取商家ID
        if (!this.merchantId) {
          this.$message.error('无法获取商家信息，请刷新页面重试')
          return
        }

        this.qrCodeLoading = true
        this.qrCodeDialogVisible = true
        this.qrCodeUrl = ''

        Logger.log('=== 生成聚合码 ===')
        Logger.log('商家ID:', this.merchantId)

        const response = await generateQrCode(this.merchantId)
        Logger.log('生成聚合码API响应:', response)

        if (response.code === 0) {
          this.qrCodeUrl = response.data.qrCodeUrl || response.data
          this.$message.success('聚合码生成成功')
        } else {
          this.$message.error(response.data?.msg || '生成聚合码失败')
        }
      } catch (error) {
        Logger.error('生成聚合码失败:', error)
        this.$message.error('生成聚合码失败: ' + (error.message || '未知错误'))
      } finally {
        this.qrCodeLoading = false
      }
    },

    // 重新生成聚合码
    async regenerateQrCode() {
      this.qrCodeUrl = ''
      await this.generateAggregationCode()
    },

    // 下载二维码
    downloadQrCode() {
      if (!this.qrCodeUrl) {
        this.$message.error('二维码未生成')
        return
      }

      try {
        // 创建一个临时的a标签来下载图片
        const link = document.createElement('a')
        link.href = this.qrCodeUrl
        link.download = `${this.merchantInfo.name || '商家'}_聚合码.png`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.$message.success('二维码下载成功')
      } catch (error) {
        Logger.error('下载二维码失败:', error)
        this.$message.error('下载二维码失败')
      }
    }
  }
}
</script>

<style scoped>
.merchant-dashboard {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  color: #303133;
  font-size: 24px;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
}

.page-description {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.header-actions {
  margin-top: 15px;
}

.qr-code-btn {
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.qr-code-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
  font-size: 24px;
}

.limit-icon {
  background: linear-gradient(135deg, #e6a23c, #f56c6c);
}

.usage-icon {
  background: linear-gradient(135deg, #909399, #606266);
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.card-unit {
  font-size: 12px;
  color: #909399;
}

.progress-container {
  margin-top: 8px;
}

.info-section {
  margin-bottom: 20px;
}

.info-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.info-content {
  padding: 10px 0;
}

.info-item {
  display: flex;
  margin-bottom: 16px;
  align-items: center;
}

.info-item label {
  width: 120px;
  color: #606266;
  font-weight: 500;
}

.info-value {
  color: #303133;
  flex: 1;
  display: flex;
  align-items: center;
}

.toggle-btn {
  margin-left: 8px;
  padding: 0;
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.no-data i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-container {
  padding: 20px 0;
}

.chart-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.donut-chart {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: conic-gradient(
    #409eff 0deg calc(var(--percentage, 0) * 3.6deg),
    #e4e7ed calc(var(--percentage, 0) * 3.6deg) 360deg
  );
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-right: 40px;
}

.donut-chart::before {
  content: '';
  position: absolute;
  width: 120px;
  height: 120px;
  background: white;
  border-radius: 50%;
}

.chart-center {
  position: relative;
  z-index: 1;
  text-align: center;
}

.percentage {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.label {
  font-size: 14px;
  color: #909399;
}

.chart-legend {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  margin-right: 8px;
}

.legend-color.used {
  background-color: #409eff;
}

.legend-color.remaining {
  background-color: #e4e7ed;
}

/* 二维码对话框样式 */
/* 对话框头部样式已使用公共样式，此处仅保留内容区域特殊样式 */
::v-deep .qr-code-dialog {
  .qr-code-content {
    text-align: center;
    padding: 20px 0;
  }

  .qr-code-info h3 {
    color: #2c3e50;
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 15px;
  }

  .qr-code-desc {
    color: #6c757d;
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 30px;
    text-align: left;
    background: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
    border-left: 4px solid #409eff;
  }

  .qr-code-container {
    margin: 20px 0;
    display: flex;
    justify-content: center;
  }

  .qr-code-image {
    max-width: 250px;
    max-height: 250px;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .qr-code-actions {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 15px;
  }

  .qr-code-loading {
    padding: 40px 0;
    color: #909399;
  }

  .qr-code-loading i {
    font-size: 24px;
    margin-bottom: 10px;
    display: block;
  }

  .dialog-footer {
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #e9ecef;
  }
}
</style>
